<template>
  <basic-container>
    <div slot="header" class="card-header clearfix">
      <span class="header-title">定时报告</span>
    </div>

    <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions" @change="handleChangeFilter">
    </cs-filter-query>

    <div class="curd-table">
      <div class="tab-header clearfix">
        <div class="tab-header-left">
          <el-button size="mini" @click="addReport">新增报告</el-button>
          <el-button size="mini" @click="delTimingReportByIds">删除报告</el-button>
        </div>
        <div class="tab-header-right">
        </div>
      </div>
      <div class="table-body">
        <el-table
          v-loading="loading"
          :data="timingReportList"
          border
          :header-cell-style="iHeaderCellStyle"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="reportName"
            label="报告名称">
          </el-table-column>
          <el-table-column
            prop="reportDateRange"
            label="数据范围"
            width="100">
            <template v-slot="{row}">
              {{ findDateRange(row.reportDateRange) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="offerId"
            label="关联订单"
            width="120">
            <template v-slot="{row}">
              {{ findOfferById(row.offerId) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="pushTarget"
            label="通知方式"
            width="100">
            <template v-slot="{row}">
              {{ findPushTarget(row.pushTarget) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="100">
            <template v-slot="{row}">
              {{ findStatus(row.status, row.startDate, row.endDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            width="100">
            <template v-slot="{row}">
              {{ findUser(row.createUser) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="更新时间"
            width="150">
          </el-table-column>
          <el-table-column
            label="操作" width="170">
            <template v-slot="{row}">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i class="el-icon-edit cs-button active"
                   @click="editOrCopyReport(row, true)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="开始" placement="top">
                <i class="el-icon-video-play cs-button" :class="row.status===0?'active':'disabled'"
                   @click="changeReportStatus(row, 1)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="暂停" placement="top">
                <i class="el-icon-video-pause cs-button" :class="row.status===1?'active':'disabled'"
                   @click="changeReportStatus(row, 0)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <i class="el-icon-copy-document cs-button"
                   :class="parseInt(row.status)===4?'disabled':'active'"
                   @click="editOrCopyReport(row, false)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i class="el-icon-delete cs-button"
                   :class="parseInt(row.status)===4?'disabled':'active'"
                   @click="delTimingReportById(row.id)"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom-page clearfix">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <el-drawer
      :title="drawerTitle+'定时报告'"
      size="800px"
      :visible.sync="drawerSwitch"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
      @close="handleCloseDrawer"
      @opened="handleOpenDrawer"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <el-form :model="reportForm" ref="reportForm" :disabled="isEdit && reportForm.status===4"
                 class="add-form" :rules="rules" label-width="100px" v-loading="editLoading">
          <div class="add-title">报告内容</div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单" prop="offerId">
                <el-select size="mini" v-model="reportForm.offerId" clearable filterable @change="getTimingReportConfig"
                           :disabled="isEdit">
                  <el-option v-for="item in offerList" :key="item.id" :value="item.id" :label="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告名称" prop="reportName">
                <el-input v-model="reportForm.reportName" size="mini" placeholder="请输入内容"
                          :disabled="reportForm.offerId === ''"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据范围" prop="reportDateRange">
                <el-select size="mini" v-model="reportForm.reportDateRange" clearable filterable
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in dateRange" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账户" prop="platformAccount">
                <el-select size="mini" v-model="reportForm.platformAccount" clearable filterable multiple collapse-tags :filter-method="typeFilter"
                           :disabled="reportForm.offerId === ''" @clear="clearAccounts" @remove-tag="removeAccountTag">
                  <el-option class="setstyle">
                    <el-tree :data="accountList" :props="{children: 'children',label: 'label'}" ref="accountTree"
                             node-key="value"
                             :filter-node-method="filterNode"
                             show-checkbox
                             default-expand-all
                             check-on-click-node @check="handleNodeClick"></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="广告维度" prop="dimensions">
                <el-select size="mini" v-model="reportForm.dimensions" clearable filterable
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in dimensionsList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据指标" prop="indicators">
                <el-select size="mini" v-model="reportForm.indicators" clearable filterable multiple multiple-limit="4"
                           collapse-tags
                           :disabled="reportForm.offerId === ''" @change="changeIndicators">
                  <el-option v-for="item in indicatorsList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="汇总指标">
                <el-select size="mini" v-model="reportForm.summary" clearable filterable multiple collapse-tags
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in summaryList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="add-title">推送配置</div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="通知方式" prop="pushTarget">
                <el-radio-group v-model="reportForm.pushTarget" @change="handleChangePush"
                                :disabled="reportForm.offerId === ''">
                  <el-radio v-for="item in pushTargetList" :key="item.value" :label="item.value">{{
                      item.label
                    }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="reportForm.pushTarget ==='0'">
              <el-form-item label="通知接收" prop="receiverAddr">
                <el-select size="mini" v-model="reportForm.receiverAddr" clearable filterable multiple
                           multiple-limit="4"
                           collapse-tags
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in userList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12"
                    v-else-if="reportForm.pushTarget ==='1'||reportForm.pushTarget ==='2'||reportForm.pushTarget ==='4'">
              <el-form-item label="通知接收" prop="receiverAddr">
                <el-input v-model="reportForm.receiverAddr" size="mini" placeholder="请输入通知群webhook地址"
                          :disabled="reportForm.offerId === ''"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="推送日期" prop="startDate">
                <el-date-picker
                  v-model="reportForm.startDate"
                  type="date"
                  size="mini"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  :disabled="reportForm.offerId === ''">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="过期日期" prop="endDate">
                <el-date-picker
                  v-model="reportForm.endDate"
                  type="date"
                  size="mini"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  :disabled="reportForm.offerId === ''">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="推送时间" prop="pushTime">
                <el-select size="mini" v-model="reportForm.pushTime" clearable filterable
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in pushTimeList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="重复" prop="sendRepeat">
                <el-select size="mini" v-model="reportForm.sendRepeat" clearable filterable
                           :disabled="reportForm.offerId === ''">
                  <el-option v-for="item in repeatList" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template v-slot:bottom>
          <el-button type="primary" size="mini" @click="previewResult">预览效果</el-button>
          <el-button type="primary" size="mini" @click="saveFrom" :disabled="btnLock || reportForm.status === 4">保存</el-button>
        </template>
      </cs-drawer-container>
      <!--预览效果-->
      <el-dialog
        title="预览效果内容请以实际发出报告为准"
        :visible.sync="previewDialog"
        :modal-append-to-body="false"
        :append-to-body="true"
        width="500px">
        <div id="message-box">
          <div id="avatar">
            <el-avatar size="small"
                       src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
          </div>
          <div id="message">
            <div class="message-item">
              <p>{{ reportForm.reportName }}</p>
              <p>{{ findDateRange(reportForm.reportDateRange) }}&nbsp;数据&nbsp;汇总</p>
              <p>花费:0.00;&nbsp;点击0;&nbsp;曝光:0</p>
              <template v-if="reportForm.dimensions === 'os'">
                <br/>
                <div>Android:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br/>
                <div>IOS:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br/>
                <div>PC:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br/>
                <div>Other:</div>
                <div>花费:0</div>
                <div>安装:0</div>
              </template>
              <template v-else-if="reportForm.dimensions === 'platform'">
                <br>
                <div>Facebook:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br>
                <div>Google:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br>
                <div>Bigo:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br>
                <div>Tiktok:</div>
                <div>花费:0</div>
                <div>安装:0</div>
                <br>
                <div>Kwai:</div>
                <div>花费:0</div>
                <div>安装:0</div>
              </template>
              <template v-else-if="reportForm.dimensions === 'country'">
                <br><div>US:</div><div>花费:0</div><div>安装:0</div>
                <br><div>UK:</div><div>花费:0</div><div>安装:0</div>
                <br><div>ID:</div><div>花费:0</div><div>安装:0</div>
                <br><div>SA:</div><div>花费:0</div><div>安装:0</div>
                <br><div>MX:</div><div>花费:0</div><div>安装:0</div>
              </template>
              <template v-else-if="reportForm.dimensions === 'account_id'">
                <br><div>44555***1394:</div><div>花费:0 </div><div>安装:0</div>
                <br><div>54646***7514:</div><div>花费:0 </div><div>安装:0</div>
                <br><div>49734***8435:</div><div>花费:0 </div><div>安装:0</div>
                <br><div>79467***3487:</div><div>花费:0 </div><div>安装:0</div>
                <br><div>46481***4673:</div><div>花费:0 </div><div>安装:0</div>
              </template>
              <template v-else-if="reportForm.dimensions === 'account_name'">
                <br><div>ppy_abc_01:</div><div>花费:0</div><div>安装:0</div>
                <br><div>ppy_abc_02:</div><div>花费:0</div><div>安装:0</div>
                <br><div>ms_abc_01:</div><div>花费:0</div><div>安装:0</div>
                <br><div>ms_abc_02:</div><div>花费:0</div><div>安装:0</div>
                <br><div>ms_abc_03:</div><div>花费:0</div><div>安装:0</div>
              </template>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-drawer>
  </basic-container>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {
  getTimingReportConfig,
  getTimingReportList,
  removeTimingReportByIds,
  submitTimingReportConfig
} from "@/api/system/timing-report-config";
import {getOfferList} from "@/api/business/offer";
import _ from 'lodash'
import {getCreateUser} from "@/api/system/operationLog";
import CsFilterQuery from '@/components/CsFilterQuery/CsFilterQuery'
import Moment from "moment";

export default {
  name: "TimingReport",
  components: {
    CsDrawerContainer,
    CsFilterQuery
  },
  data() {
    return {
      editLoading:false,
      loading: true,
      query: '',
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      // 新增定时报告弹窗
      drawerSwitch: false,
      // 弹窗表头
      drawerTitle: '',
      // 订单列表
      offerList: [],
      createUserList: [],
      // 添加表单
      reportForm: {
        id: null,
        offerId: '',
        reportName: '',
        reportDateRange: '',
        platformAccount: [],
        dimensions: '',
        indicators: [],
        summary: [],
        pushTarget: '',
        receiverAddr: '',
        startDate: '',
        endDate: '',
        pushTime: '',
        sendRepeat: ''
      },
      // 时间范围
      dateRange: [],
      // 账户树型
      accountList: [],
      accounts: {},
      // 广告维度
      dimensionsList: [],
      // 数据指标
      indicatorsList: [],
      // 通知方式
      pushTargetList: [],
      // 推送时间
      pushTimeList: [],
      // 重复表单
      repeatList: [],
      // 定时数据订单列表
      timingReportList: [],
      // 表格杜宣
      multipleSelection: [],
      //
      btnLock: false,
      // 是否编辑
      isEdit: false,
      // 预览
      previewDialog: false,
      // 当前账户下可选用户
      userList: [],
      // 日期配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      }
    }
  },
  watch: {
    // 'reportForm.offerId': function (val) {
    //   this.handleCloseDrawer()
    // }
  },
  computed: {
    // 筛选组件配置
    filterQueryOptions() {
      return [{
        value: 'offerIdList',
        label: '关联订单',
        queryList: this.offerList.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      }, {
        value: 'reportName',
        label: '报告名称',
      }, {
        value: 'reportDateRange',
        label: '数据范围',
        children: [
          {label: '上月', value: 'last_month'},
          {label: '本月', value: 'current_month'},
          {label: '上周', value: 'last_week'},
          {label: '本周', value: 'current_week'},
          {label: '过去7天', value: 'last_7_days'},
          {label: '前日', value: 'before_yesterday'},
          {label: '昨日', value: 'yesterday'},
          {label: '今日', value: 'today'},
        ]
      }, {
        value: 'pushTarget',
        label: '通知方式',
        children: [
          {
            "label": "飞书个人",
            "value": "0"
          },
          {
            "label": "飞书群",
            "value": "1"
          },
          {
            "label": "企业微信群",
            "value": "2"
          }
        ]
      }, {
        value: 'statusList',
        label: '状态',
        children: [
          {value: '1', label: '运行中'},
          {value: '0', label: '已暂停'},
          {value: '2', label: '已过期'},
          {value: '3', label: '待运行'},
          {value: '4', label: '已删除'},
        ]
      }, {
        value: 'createUserList',
        label: '创建人',
        queryList: this.createUserList.map(item => {
          return {
            label: item.realName,
            value: item.id
          }
        })
      }];
    },
    summaryList() {
      return this.indicatorsList.filter(item => this.reportForm.indicators.includes(item.value))
    },
    rules() {
      // 验证邮箱的规则
      const checkEmail = (rule, value, cb) => {
        // 验证邮箱的正则表达式
        const regEmail = /^((([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6}\,))*(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/

        if (regEmail.test(value)) {
          // 合法的邮箱
          return cb()
        }

        cb(new Error('请输入合法的邮箱'))
      }

      const rules = {
        offerId: [
          {required: true, message: '请选择订单', trigger: 'change'}
        ],
        reportName: [
          {required: true, message: '请输入报告名称', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}
        ],
        reportDateRange: [
          {required: true, message: '请选择数据范围', trigger: 'change'}
        ],
        platformAccount: [
          {type: 'array', required: true, message: '请至少选择一个账户', trigger: 'change'}
        ],
        dimensions: [
          {required: true, message: '请选择广告维度', trigger: 'change'}
        ],
        indicators: [
          {type: 'array', required: true, message: '请至少选择一个指标', trigger: 'change'}
        ],
        pushTarget: [
          {required: true, message: '请选择通知方式', trigger: 'change'}
        ],
        startDate: [
          {required: true, message: '请选择推送日期', trigger: 'change'}
        ],
        endDate: [
          {required: true, message: '请选择过期时间', trigger: 'change'}
        ],
        pushTime: [
          {required: true, message: '请选择推送时间', trigger: 'change'}
        ],
        sendRepeat: [
          {required: true, message: '请选择重复', trigger: 'change'}
        ]
      }
      if (this.reportForm.pushTarget === '0') {
        Object.assign(rules, {
          receiverAddr: [
            {type: 'array', required: true, message: '请至少选择一个接收通知人', trigger: 'change'}
          ]
        })
      } else if (this.reportForm.pushTarget === '1') {
        Object.assign(rules, {
          receiverAddr: [
            {required: true, message: '请输入通知群webhook地址', trigger: 'blur'}
          ]
        })
      } else if (this.reportForm.pushTarget === '4') {
        Object.assign(rules, {
          receiverAddr: [
            {required: true, message: '请填写接收通知', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'}
          ]
        })
      } else if (this.reportForm.pushTarget === '2') {
        Object.assign(rules, {
          receiverAddr: [
            {required: true, message: '请输入通知群webhook地址', trigger: 'blur'},
          ]
        })
      }
      return rules
    },
    // 提交的表单
    getForm() {
      let accounts = null
      let platforms = null
      try {
        // 获取选择中的账户
        accounts = this.$refs.accountTree.getCheckedNodes(true, false)
        // 获取全选的平台
        platforms = this.$refs.accountTree.getCheckedNodes().filter(item => item.hasOwnProperty('children')).map(item => item.value)
      } catch (e) {
        console.error(e)
      }
      if (!!accounts && !!platforms) {
        // 预定义数据
        const data = []
        // 拼装账户数据
        for (const dataKey in this.accounts) {
          const list = this.accounts[dataKey].filter(item => accounts.includes(item))
          data.push({
            platform: dataKey,
            account_list: list.map(item => item.value),
            all: platforms.includes(dataKey)
          })
        }
        let receiverAddr
        // 接收通知
        if (this.reportForm.pushTarget === '0') {
          receiverAddr = this.reportForm.receiverAddr.join(',')
        } else {
          receiverAddr = this.reportForm.receiverAddr
        }
        return {
          id: this.reportForm.id,
          offerId: this.reportForm.offerId,
          reportName: this.reportForm.reportName,
          reportDateRange: this.reportForm.reportDateRange,
          platformAccountJson: JSON.stringify({data}),
          dimensions: this.reportForm.dimensions,
          indicators: this.reportForm.indicators.join(','),
          summary: this.reportForm.summary.join(','),
          pushTarget: this.reportForm.pushTarget,
          startDate: this.reportForm.startDate,
          endDate: this.reportForm.endDate,
          pushTime: this.reportForm.pushTime,
          sendRepeat: this.reportForm.sendRepeat,
          receiverAddr
        }
      } else {
        return null
      }
    }
  },
  async created() {
    await this.getOfferList()
    await this.getCreateUserList()
    await this.getTimingReportList()
  },
  methods: {

    handleChangeFilter(val) {
      this.query = val
      this.page.current = 1
      this.getTimingReportList();
    },


    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getTimingReportList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getTimingReportList()
    },
    // 获取用户数据列表
    async getCreateUserList() {
      const {data: {data: res}} = await getCreateUser()
      this.createUserList = res
      // console.log(this.createUserList)
    },
    // 获取订单数据
    async getTimingReportConfig(val) {
      try {
        const {data: res} = await getTimingReportConfig({offerId: val})
        // console.log('res', res)
        //时间范围
        this.dateRange = res.data.dateRange
        // 账户列表
        this.wrapAccountList(res.data.accounts)
        this.accounts = res.data.accounts
        // 广告维度
        this.dimensionsList = res.data.dimensions
        this.indicatorsList = res.data.indicators
        this.pushTargetList = res.data.pushTarget
        this.pushTimeList = res.data.pushTime
        this.repeatList = res.data.repeat
        this.userList = res.data.userList
        this.reportForm.reportName = ''
        this.reportForm.reportDateRange = ''
        this.reportForm.platformAccount = []
        this.reportForm.dimensions = ''
        this.reportForm.indicators = []
        this.reportForm.summary = []
        this.reportForm.pushTarget = ''
        this.reportForm.receiverAddr = ''
        this.reportForm.startDate = ''
        this.reportForm.endDate = ''
        this.reportForm.pushTime = ''
        this.reportForm.sendRepeat = ''
        // this.$refs.reportForm.resetFields()
      } catch (e) {
        console.error(e)
      }
    },
    // 获取订单列表
    async getOfferList() {
      const {data: res} = await getOfferList()
      if (res.code !== 200) return this.$message.error('获取订单列表失败')
      this.offerList = res.data
    },
    // 包装账户列表
    wrapAccountList(obj) {
      this.accountList = []
      for (let key in obj) {
        this.accountList.push({
          value: key,
          label: key,
          children: obj[key]
        })
      }
    },
    // 账户选择
    handleNodeClick(data, self, child) {
      let datalist = this.$refs.accountTree.getCheckedNodes(true)
      this.reportForm.platformAccount = datalist.map(item => item.value)
    },
    typeFilter(value) {
      this.$refs.accountTree.filter(value)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 数据指标改变
    changeIndicators() {
      this.reportForm.summary = this.reportForm.summary.filter(item => this.reportForm.indicators.includes(item))
    },
    // 保存表单
    saveFrom() {
      this.$refs.reportForm.validate(async valid => {
        if (!valid) return
        if (+new Date(this.reportForm.startDate) >= +new Date(this.reportForm.endDate)) return this.$message.warning('过期日期不能小于推送日期')
        this.btnLock = true
        try {
          const {data: res} = await submitTimingReportConfig(this.getForm)
          console.log('保存', res)
          if (res.code !== 200) return this.$message.error('保存失败')
          this.$message.success('保存成功')
          await this.getTimingReportList()
          this.drawerSwitch = false
          this.btnLock = false
        } catch (e) {
          this.btnLock = false
        }

      })
    },
    // 获取定时数据订单列表
    async getTimingReportList(params = {}) {
      this.loading = true
      try {
        const {data: res} = await getTimingReportList(this.query, this.page)
        this.loading = false
        this.total = res.data.total
        this.timingReportList = res.data.records
        // console.log('list', res)
      } catch (e) {
        this.loading = false
        console.error(e)
      }
      console.log(this.query)
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
    },
    // 删除报告S
    async delTimingReportByIds() {
      if (this.multipleSelection.length === 0) return this.$message.warning('请先勾选数据')
      this.$confirm('批量删除' + this.multipleSelection.length + '条报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await removeTimingReportByIds(this.multipleSelection.join(','))
        if (res.code !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        await this.getTimingReportList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 单体删除
    delTimingReportById(id) {
      this.$confirm('删除报告定时报告将停止法发送通知消息，是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await removeTimingReportByIds(id)
        if (res.code !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        await this.getTimingReportList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新增报告
    addReport() {
      this.isEdit = false
      this.drawerSwitch = true
      this.reportForm.id = null
      this.drawerTitle = '新增'
    },
    // 改变状态
    async changeReportStatus(row, status) {
      if (row.status == status) return
      if (status) {
        const {data: res} = await submitTimingReportConfig({id: row.id, status})
        if (res.code !== 200) return this.$message.error('状态改变失败')
        await this.getTimingReportList()
      } else {
        this.$confirm('暂停后定时报告将停止法发送通知消息，是否继续', '提示', {
          confirmButtonText: '暂停',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await submitTimingReportConfig({id: row.id, status})
          if (res.code !== 200) return this.$message.error('状态改变失败')
          await this.getTimingReportList()
        }).catch(() => {
        })
      }

    },
    // 修改报告
    async editOrCopyReport(row, isEdit) {
      this.drawerSwitch = true
      this.editLoading = true
      this.isEdit = isEdit
      this.drawerTitle = isEdit ? '编辑' : '复制'
      let rowCopy = _.cloneDeep(row)
      this.reportForm.id = isEdit ? rowCopy.id : null
      await this.getTimingReportConfig(rowCopy.offerId)
      this.reportForm.offerId = rowCopy.offerId
      this.reportForm.reportName = isEdit ? rowCopy.reportName : ''
      this.reportForm.reportDateRange = rowCopy.reportDateRange
      this.filterAccounts(rowCopy.platformAccountJson)
      this.reportForm.dimensions = rowCopy.dimensions
      this.reportForm.indicators = rowCopy.indicators === '' ? [] : rowCopy.indicators.split(',')
      this.reportForm.summary = rowCopy.summary === '' ? [] : rowCopy.summary.split(',')
      this.reportForm.pushTarget = rowCopy.pushTarget
      this.reportForm.receiverAddr = rowCopy.pushTarget === '0' ? rowCopy.receiverAddr.split(',') : row.receiverAddr
      this.reportForm.startDate = rowCopy.startDate
      this.reportForm.endDate = rowCopy.endDate
      this.reportForm.pushTime = rowCopy.pushTime
      this.reportForm.sendRepeat = rowCopy.sendRepeat
      this.reportForm.status = rowCopy.status
      this.editLoading = false
    },
    // 账户的JSON转换到表单回显
    filterAccounts(val) {
      const {data: accounts} = JSON.parse(val)
      const accountKeys = _.flatten(accounts.map(item => item.account_list))
      const platforms = accounts.filter(item => item.all).map(item => item.platform)
      this.$nextTick(() => {
        for (const accountKey of accountKeys) {
          this.$refs.accountTree.setChecked(accountKey, true)
        }
        this.$nextTick(() => {
          for (const platform of platforms) {
            this.$refs.accountTree.setChecked(platform, true, true)
          }
        })
      })
      this.reportForm.platformAccount = accountKeys
    },
    findOfferById(id) {
      try {
        return this.offerList.find(item => item.id === id)['name']
      } catch (e) {
        return ''
      }

    },
    findDateRange(val) {
      if (!val) return
      const data = [
        {
          "label": "上月(" + Moment().startOf('month').subtract(1, 'months').format("yyyy-MM-DD") + "至" + Moment().startOf('month').format("yyyy-MM-DD") + ")",
          "value": "last_month"
        },
        {
          "label": "本月(" + Moment().startOf('month').format("yyyy-MM-DD") + "至" + Moment().startOf('month').add(1, "months").format("yyyy-MM-DD") + ")",
          "value": "current_month"
        },
        {
          "label": "上周(" + Moment().startOf('week').subtract(1, "weeks").format("yyyy-MM-DD") + "至" + Moment().startOf('week').format("yyyy-MM-DD") + ")",
          "value": "last_week"
        },
        {
          "label": "本周(" + Moment().startOf('week').format("yyyy-MM-DD") + "至" + Moment().startOf('week').add(1, "weeks").format("yyyy-MM-DD") + ")",
          "value": "current_week"
        },
        {
          "label": "过去7天(" + Moment().subtract(7, "days").format("yyyy-MM-DD") + "至" + Moment().format("yyyy-MM-DD") + ")",
          "value": "last_7_days"
        },
        {
          "label": "前日(" + Moment().subtract(2, "days").format("yyyy-MM-DD") + ")",
          "value": "before_yesterday"
        },
        {
          "label": "昨日(" + Moment().subtract(1, "days").format("yyyy-MM-DD") + ")",
          "value": "yesterday"
        },
        {
          "label": "今日(" + Moment().format("yyyy-MM-DD") + ")",
          "value": "today"
        }
      ]
      try {
        return data.find(item => item.value === val)['label']
      } catch (e) {
        return ''
      }
    },
    findPushTarget(val) {
      const data = [
        {
          "label": "飞书个人",
          "value": "0"
        },
        {
          "label": "飞书群",
          "value": "1"
        },
        {
          "label": "企业微信群",
          "value": "2"
        }
      ]
      try {
        return data.find(item => item.value === val)['label']
      } catch (e) {
        return ''
      }

    },
    findUser(val) {
      try {
        return this.createUserList.find(item => item.id === val)['realName']
      } catch (e) {
        return ''
      }

    },
    findStatus(status, startDate, endDate) {
      const now = +new Date()
      const start = +new Date(startDate)
      const end = +new Date(endDate)
      if (now < start && status === 1) {
        return '待运行'
      } else if (now > end) {
        return status===4?"已删除":'已过期'
      } else {
        return status === 1 ? '运行中' : '已暂停'
      }
    },
    // 关闭抽屉处理
    handleCloseDrawer() {
      this.reportForm = {
        offerId: '',
        reportName: '',
        reportDateRange: '',
        platformAccount: [],
        dimensions: '',
        indicators: [],
        summary: [],
        pushTarget: '',
        receiverAddr: '',
        startDate: '',
        endDate: '',
        pushTime: '',
        sendRepeat: '',
      }
      this.$refs.reportForm.resetFields()
    },
    // 预览效果
    previewResult() {
      this.$refs.reportForm.validate(async valid => {
        if (!valid) return
        this.previewDialog = true
      })
    },
    // 清除账户
    clearAccounts() {
      this.reportForm.platformAccount = []
      this.$refs.accountTree.setCheckedKeys([])
    },
    // 移除账户多选框中tag
    removeAccountTag(tag) {
      this.$refs.accountTree.setChecked(tag, false)
    },
    handleChangePush(lable) {
      if (lable === 0) {
        this.reportForm.receiverAddr = []
      } else if (lable === 1 || lable === 2) {
        this.reportForm.receiverAddr = ''
      } else {
        this.reportForm.receiverAddr = ''
      }
      this.$refs.reportForm.clearValidate()
    },
    handleOpenDrawer() {
      this.$refs.reportForm.clearValidate()
    }
  }
}
</script>

<style lang="scss" scoped>
.card-header {
  .header-title {
    float: left;
    font-size: 16px;
    font-weight: bold;
  }

  .header-right {
    float: right;
  }
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    margin-top: 15px;

    .el-pagination {
      float: right;
      margin-bottom: 30px;
    }
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
      }
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

.add-form {
  padding: 0 25px;

  .add-title {
    padding: 20px;
    font-size: 16px;
    font-weight: bold;
  }
}


.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}

.el-select, .el-date-editor {
  width: 100%;
}

.cs-button {
  cursor: pointer;
  font-size: 16px;
}

.active {
  color: #409EFF;
}

.disabled {
  cursor: default !important;
}

#message-box {
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: start;

  #avatar {
    padding: 5px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    align-items: center;
  }

  #message {
    box-sizing: border-box;
    padding: 10px;
    width: 100%;

    .message-item {
      padding: 5px 15px;
      background-color: #EEE;
      border-radius: 5px;
    }
  }
}

p {
}
</style>
